package ball.sneaker.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 *
 * @author Arthur
 */
public class Connection implements Runnable{

    static public final int DEFAULT_SERVER_PORT = 443;

    /**
     * logger
     */
    static private Logger logger;
    static{
        logger = Logger.getLogger("SystemLog");
    }

    /**
     * Socket through which the communication is established
     */
    Socket socket;

    public Connection(Socket s) {
        socket = s;
    }
    
    public void run() {
        logger.info(">> run()");

        ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
        try {
            InputStream is = socket.getInputStream();
            int n = is.available();
            byte[] buffer = new byte[n];
            is.read(buffer,0, n);
            String s = new String(buffer);

//            if(is!= null){
//
//                int i=0;
//                int read = 0;
//                while((read = is.read(buffer,i, imax-i))!=-1){
//                   i+=read;
//                }
//                is.close();
//                String resp = new String(buffer);
//                logger.info("response: \n" + resp);
//
//            }

            logger.info("request: \n" + s);

            logger.info("loading keystore");
            KeyStore ks = null;
            try {
//                ks = KeyStore.getInstance("JKS");
//                char[] passphrase = "certif".toCharArray();
//                ClassLoader loader = Connection.class.getClassLoader();
//                ks.load(loader.getResourceAsStream("sneakerClient.keystore"),passphrase);
//
//                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
//                kmf.init(ks, passphrase);
//                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
//                tmf.init(ks);
                X509TrustManager xtm = new X509TrustManager() {

                    public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                        
                    }

                    public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
                       
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };

                
                TrustManager[] trustAllCerts=new TrustManager[]{xtm};

                SSLContext ssl = SSLContext.getInstance("TLS");
                ssl.init(null, trustAllCerts, null);
                HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
                HostnameVerifier hv = new HostnameVerifier() {
                    public boolean verify(String string, SSLSession ssls) {
                        return true;
                    }
                };
                
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            } catch (KeyManagementException ex) {
                Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
            } 

            logger.info("Connection to remote https server");
            URL url = new URL("https://localhost/");
            URLConnection con = url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.connect();

            OutputStream remoteOs = con.getOutputStream();
            remoteOs.write(buffer);
            remoteOs.flush();
            remoteOs.close();
           
            

            int imax = con.getContentLength();
            logger.info(imax +" bytes to read");

            buffer = new byte[imax];

            InputStream remoteIs = con.getInputStream();
            String resp = "";
            if(remoteIs!= null){
                
                int i=0;
                int read = 0;
                while((read = remoteIs.read(buffer,i, imax-i))!=-1){
                   i+=read;
                }
                remoteIs.close();
//                resp = new String(buffer);
//                logger.info("response: \n" + resp);

            }
            
            
            
            OutputStream os = socket.getOutputStream();
            String _404 = "<html>ERROR 404</html>";
            os.write(buffer);
            os.flush();
            os.close();
            

        } catch (IOException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        logger.info("<< run()");
    }
    
}
